package com.ruoyi.menu.service;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.menu.entity.TbMenu;
import com.ruoyi.menu.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class MenuService {
    @Autowired
    private MenuMapper tbMenuMapper;

    /**
     * 查询菜品
     *
     * @param id 菜品主键
     * @return 菜品
     */
    public TbMenu selectTbMenuById(Long id)
    {
        return tbMenuMapper.selectTbMenuById(id);
    }

    /**
     * 查询菜品列表
     *
     * @param tbMenu 菜品
     * @return 菜品
     */
    public List<TbMenu> selectTbMenuList(TbMenu tbMenu)
    {
        return tbMenuMapper.selectTbMenuList(tbMenu);
    }

    /**
     * 新增菜品
     *
     * @param tbMenu 菜品
     * @return 结果
     */
    public int insertTbMenu(TbMenu tbMenu)
    {
        tbMenu.setCreateTime(DateUtils.getNowDate());
        return tbMenuMapper.insertTbMenu(tbMenu);
    }

    /**
     * 修改菜品
     *
     * @param tbMenu 菜品
     * @return 结果
     */
    @Transactional
    public int updateTbMenu(TbMenu tbMenu)
    {
        return tbMenuMapper.updateTbMenu(tbMenu);
    }

    /**
     * 批量删除菜品
     *
     * @param ids 需要删除的菜品主键
     * @return 结果
     */
    public int deleteTbMenuByIds(Long[] ids)
    {
        return tbMenuMapper.deleteTbMenuByIds(ids);
    }

    /**
     * 删除菜品信息
     *
     * @param id 菜品主键
     * @return 结果
     */
    public int deleteTbMenuById(Long id)
    {
        return tbMenuMapper.deleteTbMenuById(id);
    }

    public String addMenuList(List<TbMenu> menus) {
        StringBuilder successMsg = new StringBuilder();
        for (TbMenu menu : menus) {
            menu.setMenuLostTime(new Date());
            tbMenuMapper.insertTbMenu(menu);
            successMsg.append(menu.getMenuName()+"添加成功");
        }

        return successMsg.toString();
    }

    @Async("taskExecutor")
    public AjaxResult importExcel(MultipartFile file) throws Exception {
        System.out.println("线程2"+Thread.currentThread().getName());
        ExcelUtil<TbMenu> util = new ExcelUtil<TbMenu>(TbMenu.class);
        List<TbMenu> menus = util.importExcel(file.getInputStream());
        String message = this.addMenuList(menus);
        return AjaxResult.success(message);
    }

}
